/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-dealer
*
* @File name : DloadImgFromQy.java
*
* @Author : Administrator
*
* @Date : 2017年12月14日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年12月14日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.dealer.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.marketing.common.DloadImgUtil;

/**
 * @author Administrator 
 * @date 2017年12月14日
 */

public class DloadImgFromQy {

    private static Logger logger = Logger.getLogger(DloadImgUtil.class);

    /**
     * 根据内容类型判断文件扩展名
     *
     * @param contentType 内容类型
     * @return
     */
    public static String getFileexpandedName(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType)) fileEndWitsh = ".jpg";
        else if ("audio/mpeg".equals(contentType)) fileEndWitsh = ".mp3";
        else if ("audio/amr".equals(contentType)) fileEndWitsh = ".amr";
        else if ("video/mp4".equals(contentType)) fileEndWitsh = ".mp4";
        else if ("video/mpeg4".equals(contentType)) fileEndWitsh = ".mp4";
        return fileEndWitsh;
    }

    /**
     * 获取媒体文件
     * 
     * @param accessToken 接口访问凭证
     * @param mediaId 媒体文件id
     * @param savePath 文件在本地服务器上的存储路径
     */
    public static List<String> downloadMedia(List<String> list, String token) {
        String accessToken = token;
        // 测试环境
        // String savePath = "/home/lyh_test/file_remote/forum";
        // String uri = "http://wxtest.gmmc.com.cn/wx/fs01/forum/";
        // 生产环境
        String savePath = "/home/appadmin/appfile/fs01/driveAgreement";
        String uri = "http://carowner.yonyouauto.com/fs01/driveAgreement/";
        logger.info("传入的toen为：" + accessToken);
        List<String> result = new ArrayList<String>();
        String filePath = null;
        String fileExt = null;
        for (int a = 0; a < list.size(); a++) {
            String mediaId = list.get(a);
            File file = null;
            // 拼接请求地址
            String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
            requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
            try {
                URL url = new URL(requestUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setRequestMethod("GET");

                if (!savePath.endsWith("/")) {
                    savePath += "/";
                }
                // 根据内容类型获取扩展名
                fileExt = DloadImgUtil.getFileexpandedName("image/jpeg");
                // 将mediaId作为文件名
                filePath = savePath + mediaId + fileExt;
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                file = new File(filePath);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[8096];
                int size = 0;
                // 代码扫描 8 10.18
                try {
                    while ((size = bis.read(buf)) != -1)
                        fos.write(buf, 0, size);
                } catch (Exception e) {
                    filePath = null;
                    String error = String.format("下载媒体文件失败：%s", e);
                    logger.info(error);
                } finally {
                    fos.close();
                    bis.close();
                    conn.disconnect();
                }
                String info = String.format("下载媒体文件成功，filePath=" + filePath);
                logger.info(info);
            } catch (Exception e) {
                filePath = null;
                String error = String.format("下载媒体文件失败：%s", e);
                logger.info(error);
            }
            result.add(uri + mediaId + fileExt);
        }
        return result;
    }
}
